<?php

namespace app\index\controller;

use app\baidu\model\AdminSetting;
use app\card\model\Collection;
use app\card\model\Config;
use app\card\model\CardCount;
use app\card\model\User;
use app\card\model\UserInfo;
use app\card\model\UserPhone;
use app\card\model\UserSk;
use app\card\service\UserService;
use app\redbag\model\Invitation;
use app\restaurant\model\ClassDate;
use longbingcore\tools\LongbingDefault;
use think\App;
use think\facade\Db;
use think\Response;
use app\baidu\model\AdminActive;

class Login
{
    //  小程序登陆每个用户产生的唯一表示
    protected $code = '';

    protected $uniacid;
    protected $request;
    protected $_param;
    protected $_input;

    function __construct(App $app)
    {
        global $_GPC, $_W;

        $this->request = $app->request;

        //获取param
        $this->_param = $this->request->param();

        $this->_input = json_decode($this->request->getInput(), true);
        //获取uniacid
        if (!isset($this->_param['i']) || !$this->_param['i']) {
//          return $this->error([ 'code' => 400, 'error' => 'need uniacid' ]);
            echo json_encode(['code' => 400, 'error' => 'need uniacid']);
            exit;
        }
        $this->uniacid = $this->_param['i'];
    }

    /**
     * @Purpose: 小程序登陆接口
     *
     * @Param: string $code 小程序传过来的登陆code
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    function index()
    {
        //获取token
        if (!isset($this->_param['code']) || !$this->_param['code']) {

            return $this->error(['code' => 400, 'error' => 'need code']);

        }

        global $_GPC, $_W;

        $code    = $this->_param['code'];

        $uniacid = $this->_param['i'];
        //  是否是微擎
        $config = longbingGetAppConfig($this->uniacid);

        $appid  = $config['appid'];

        $appsecret = $config['app_secret'];

        $from_id = isset( $this->_param[ 'from_id' ] ) ? $this->_param[ 'from_id' ] : '';
        //新增19.12.3
        if(!is_numeric( $from_id ) ){
            $result = longbingGetWxCode($from_id ,$this->uniacid , $is_update = false);
            if(!is_null($result) && array_key_exists("data", $result) ){
                $result = \think\Collection::make($result['data'])->toArray();
                if(array_key_exists("user_id", $result) ){
                    $from_id = $result['user_id'] ;
                }else if(array_key_exists("pid", $result) ){
                    $from_id = $result['pid'] ;
                }

            }
        }
        //如果是扫桌码进来
        if(!empty($this->_param['table_id'])){

            $date_model = new ClassDate();
            //通过桌号找到员工
            $store = $date_model->tableFindStaff($this->_param['table_id']);
            //如果抱错则没有员工
            if(!empty($store['code'])){

                $from_id = '';

            }else{

                $from_id = $store['staff_id'];
            }

        }

        $is_qr = isset($this->_param['is_qr']) ? $this->_param['is_qr'] : '';

        $encryptedData = isset($this->_param['encryptedData']) ? $this->_param['encryptedData'] : '';

        $iv = isset($this->_param['iv']) ? $this->_param['iv'] : '';

        $userModel = new User();
        //  从微信获取openid等
        $url  = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";


        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );

        $info = file_get_contents($url ,false, stream_context_create($arrContextOptions));

        $info = @json_decode($info, true);

        if (!is_array($info)) {

            echo json_encode(['code' => 402, 'error' => 'need code' . $info]);

            exit;
        }
        //  微信端返回错误
        if (isset($info['errcode'])) {

            echo json_encode(['code' => 402, 'error' => $info['errcode'] . ', errmsg: ' . $info['errmsg']]);
            exit;
        }
        if (!isset($info['session_key'])) {

            echo json_encode(['code' => 402, 'error' => 'session_key not exists']);

            exit;
        }

        if (!isset($info['unionid'])) {

        }
        $session_key = $info['session_key'];

        $openGId     = '';

        if ($encryptedData) {

            $data = null;
            //  解密
            $errCode = decryptDataLongbing($appid, $session_key, $encryptedData, $iv, $data);

            //  判断解密是否有错误
            if ($errCode == 0) {
                $data = json_decode($data, true);
                $openGId = $data['openGId'];
            }
        }
        $randName = getRandStr(4);

        if (!isset($info['openid'])) {
            echo json_encode(['code' => 402, 'error' => 'openid not exists']);
            exit;
        }

        $openid = $info['openid'];
        $unionid = isset($info['unionid']) ? $info['unionid'] : '';


        $user = '';
        //  检查用户有没有从获客文章来的数据
        if ($unionid) {
            $userFromArticle = $userModel->where([['unionid', '=', $unionid], ['openid', '<>', $openid],
                ['uniacid', '=', $uniacid], ['is_article', '=', 1]])->find();

            $user = $userModel->where(['openid' => $openid, 'uniacid' => $uniacid])->find();
            if ($user && $userFromArticle) {
                $cardModel = new CardCount();
                $cardModel->update(['user_id' => $user->id,], ['user_id' => $userFromArticle->id]);
                $user->unionid = $unionid;
                $user->save();
            }
        }
        if (!$user) {
            $user = $userModel->where([['openid', '=', $openid], ['uniacid', '=', $uniacid]])->find();
        }


        //新用户
        if (!$user) {

            $insertData = ['openid' => $openid];
            $insertData['nickName'] = $randName;
            $insertData['scene'] = isset($this->_param['scene']) ? $this->_param['scene'] : 0;


            //获取系统设置
            $whereSetting['uniacid']=$uniacid;
            //file_put_contents(APP_PATH."/a.txt",'unionid：'.$uniacid, FILE_APPEND | LOCK_EX);

            $setting =Db::name('longbing_card_config')->where(['uniacid'=>$uniacid])->find();

            $formUser = $userModel->where(['id' => $from_id, 'uniacid' => $uniacid])->find();
            //开启分销的时候特殊处理,当开启分销状态，并且邀请用户是分销员时，绑定对应关系
            if($setting['distribution_user_examine']==1 && $formUser['distribution']==2 && $formUser['is_staff']==0) {
                //新增判断邀请用户是否是分销员，如果是分销员，不进行绑定，在审核分销员的时候进行绑定
                $insertData['pid']=$from_id;
            }
            else if($setting['distribution_user_examine']== 0){

                $insertData['pid']=$from_id;
            }

            $insertData['uniacid'] = $uniacid;
            $insertData['is_qr'] = $is_qr;
            $insertData['unionid'] = $unionid;
            $insertData['ip'] = 0;
            $insertData['is_staff'] = 0;
            if ($openGId) {
                $insertData['openGId'] = $openGId;
            }

            if (isset($this->_param['is_group'])) {
                $insertData['is_group'] = $this->_param['is_group'];
            }
            if (isset($this->_param['type'])) {
                $insertData['type'] = $this->_param['type'];
            }
            if (isset($this->_param['target_id'])) {
                $insertData['target_id'] = $this->_param['target_id'];
            }

            $result = $userModel->save($insertData);

            if ($result) {
                $uid = $userModel->id;

                $user = $userModel->where(['openid' => $openid, 'uniacid' => $uniacid])->find();
                if ($openGId) {
                    $user['openGId_2'] = $openGId;
                }
                $user['phone'] = '';

                //红包邀请
                if(!empty($from_id)&&!empty($this->_param['redbag_active_id'])){
                    //邀请模型
                    $invitation = new Invitation();

                   // dump($from_id,$user['id'],$this->_param['redbag_active_id'],$uniacid);exit;
                    //邀请
                    $invitation->addInvitation($from_id,$user['id'],$this->_param['redbag_active_id'],$uniacid);
                }
            }

            //  自动分配员工
            $configModel = new Config();

            //  获取配置
            $configInfo = $configModel->where('uniacid', '=', $uniacid)->find();
            //  判断有没有获取到配置信息，并且配置信息众是否有配置开关，并且开关打开没有
            //if ($configInfo && isset($configInfo['auto_switch']) && $configInfo['auto_switch'] && $from_id == 0) {
            if ($configInfo  && $from_id == 0) {
                //  判断有没有分配方式
                if ($configInfo && isset($configInfo['auto_switch_way']) && $configInfo['auto_switch_way']) {
                    $tmpClientId = $userModel->id;
                    if ($tmpClientId) {
                        $clientInfo = false;
                        $prefix = \think\facade\Config::get('database.connections.mysql.prefix');

                        //  随机分配
                        if ($configInfo['auto_switch_way'] == 1) {

                            //$sql = "select * from " . $prefix . "longbing_card_user_info where uniacid = $uniacid AND is_staff = 1 AND is_default = 1 AND fans_id != 0 order by rand() limit 0,1";

                            $sql =<<<SQL
SELECT
	b.*
FROM
	{$prefix}longbing_card_user as a
LEFT JOIN {$prefix}longbing_card_user_info as b
on  a.id = b.fans_id
WHERE
	a.uniacid = {$uniacid}
AND	b.uniacid = {$uniacid}
AND b.is_staff = 1
AND b.is_default = 1
AND b.fans_id != 0
ORDER BY
	rand()
LIMIT 0,
 1
SQL;


                            $clientInfo = Db::query($sql);

                        }
                        //  按顺序分配
                        if ($configInfo['auto_switch_way'] == 2) {
                            //$sql = "select * from " . $prefix . "longbing_card_user_info where uniacid = $uniacid AND is_staff = 1 AND is_default = 1 AND fans_id != 0 order by auto_count ASC limit 0,1";

                            $sql =<<<SQL
SELECT
	b.*
FROM
	{$prefix}longbing_card_user as a
LEFT JOIN {$prefix}longbing_card_user_info as b
on  a.id = b.fans_id
WHERE
	a.uniacid = {$uniacid}
AND	b.uniacid = {$uniacid}
AND b.is_staff = 1
AND b.is_default = 1
AND b.fans_id != 0
ORDER BY
	auto_count ASC
LIMIT 0,
 1
SQL;

                            $clientInfo = Db::query($sql);
                        }
                       // file_put_contents(APP_PATH."/a.txt",'clientInfo：'.json_encode($clientInfo), FILE_APPEND | LOCK_EX);

                        if ($clientInfo) {
                            $clientInfo = $clientInfo[0];
                            $tmpStaffId = $clientInfo['fans_id'];
                            $auto_count = $clientInfo['auto_count'];
                            if (empty($auto_count)) $auto_count = 0;
                            $auto_count = $auto_count + 1;
                            $collectionModel = new Collection();
                            $collectionModel->uniacid = $uniacid;
                            $collectionModel->uid = $tmpClientId;
                            $collectionModel->to_uid = $tmpStaffId;
                            $collectionModel->from_uid = $tmpStaffId;
                            $collectionModel->status = 1;
                            $collectionModel->is_auto = 1;
                            $autoResult = $collectionModel->save();
                            //file_put_contents(APP_PATH."/a.txt",'autoResult：'.$autoResult, FILE_APPEND | LOCK_EX);
                            if (!empty($autoResult)) {
                                $user['autoCardId'] = $tmpStaffId;
//                              $userModel->pid       = $tmpStaffId;
//                              $userModel->last_staff_id = $tmpStaffId;
//                              $userModel->save();
                                //更新用户的pid
                                $userModel = new User();
                                $user['pid'] = $tmpStaffId;
                                $user['last_staff_id'] = $tmpStaffId;
                                //file_put_contents(APP_PATH."/a.txt",'setting：'.json_encode($setting), FILE_APPEND | LOCK_EX);
                                $updateUser=$setting['distribution_user_examine'] == 0
                                    ? ['last_staff_id' => $tmpStaffId,'pid'=>$tmpStaffId]
                                    : ['last_staff_id' => $tmpStaffId];
                                //file_put_contents(APP_PATH."/a.txt","updateUser：".json_encode($updateUser), FILE_APPEND | LOCK_EX);
                                $userModel->updateUser(['id' => $user['id']],$updateUser );
                                //更新员工分配信息
                                $userInfoModel = new UserInfo();
                                $data = $userInfoModel->updateUser(['fans_id' => $tmpStaffId], ['auto_count' => $auto_count]);
//                              $data = $userInfoModel->where( [ 'id' => $clientInfo[ 'id' ] ] )
//                                            ->inc( 'auto_count' );
                            }
                        }
                    }
                }
            }

        } else { //老用户

            //处理第三方平台ID
            if ($unionid) {
                $user->unionid = $unionid;
                $user->save();
            }

            $userPhoneModel = new UserPhone();
            $phone = $userPhoneModel->where([['user_id', '=', $user['id']], ['uniacid', '=', $uniacid]])->find();
            $uid = $user['id'];
            $user['phone'] = $phone ? $phone['phone'] : '';
            if ($openGId) {
                $user['openGId_2'] = $openGId;
            }
        }

        if (!$uid) {
            echo json_encode(['code' => 402, 'error' => 'login fail']);
            exit;
        }
        //By.jingshuixian 更新用户最新的信息
        UserService::delUserInfoCache($this->uniacid,$uid) ;
        //  检查用户的sk记录状态
        $skModel = new UserSk();
        $check_sk = $skModel->where('user_id', '=', $uid)->find();
        //        zDump($check_sk);
        if ($check_sk) {
            //            $check_sk->sk = $session_key;
            //            $check_sk->save();
            $skModel->update(['sk' => $session_key, 'update_time' => time()], ['user_id' => $uid]
            );
        } else {
            $skModel->sk = $session_key;
            $skModel->user_id = $uid;
            $skModel->uniacid = $uniacid;
            $skModel->create_time = time();
            $skModel->update_time = time();
            $skModel->save();
        }

        $_W['uid'] = $uid;

        //  是否是微擎
        if (defined('IS_WEIQIN') && IS_WEIQIN) {

            $user = handleImagesWe7Local($user, ['qr_path', 'pay_qr'], ',');
        }

        if (!isset($user['autoCardId'])) {

            $user['autoCardId'] = 0;
        }

        if ($user['last_staff_id'] == 0) {

            $lastInfo = CardCount::alias('a')
                ->join('longbing_card_user b', 'a.to_uid = b.id')
                ->where(['a.user_id' => $uid, 'b.is_staff' => 1])
                ->order(['a.id' => 'desc'])
                ->limit(1)
                ->find();
            if ($lastInfo) {
                $user['last_staff_id'] = $lastInfo['to_uid'];
            }
        }else{
            $staff_user = $userModel->where(['id'=>$user['last_staff_id'],'is_staff'=>1])->find();

            if(empty($staff_user)){
                $lastInfo = CardCount::alias('a')
                    ->join('longbing_card_user b', 'a.to_uid = b.id')
                    ->where(['a.user_id' => $uid, 'b.is_staff' => 1])
                    ->order(['a.id' => 'desc'])
                    ->limit(1)
                    ->find();
                if ($lastInfo) {
                    $user['last_staff_id'] = $lastInfo['to_uid'];
                }
            }
        }
        //  有分享人
        if ($from_id) {

            $user['last_staff_id'] = $from_id;
        }
        //判断last_staff_id是否是员工 chenniang
        $staff_user = $userModel->where(['id'=>$user['last_staff_id'],'is_staff'=>1])->count();
        //如果不是
        if(empty($staff_user)){
            //模型
            $collectionModel = new Collection();
            //分配一个
            $user['last_staff_id'] = $collectionModel->getCard($uid,$uniacid);
        }

        $key = 'longbing_user_autograph_' . $uid;
        $key = md5($key);
        $user = $user->toArray();


        $user['need_auth'] = 0;
        if (!$user['avatarUrl']) {
            $user['need_auth'] = 1;
        }

        $result = setCache($key, $user, 7200, $uniacid);

        if (!$result) {
            echo json_encode(['code' => 402, 'error' => 'login fail']);
            exit;
        }

        if (!isset($user['autoCardId'])) {
            $user['autoCardId'] = 0;
        }
        //获取sk数据
        longbingGetUserSk($uid, $uniacid, true);
        //By.jingshuixian  判断是否需要初始化第一个用户为员工
        event("UserLoginApp" , $user);

        if(!isset($user['avatarUrl']) || empty($user['avatarUrl']) ) $user['avatarUrl'] =  LongbingDefault::$avatarImgUrl;
        //By.jingshuixian 更新用户最新的信息
        UserService::delUserInfoCache($this->uniacid,$uid) ;

        echo json_encode(['code' => 200, 'data' => ['user_id' => $uid, 'user' => $user, 'autograph' => $key]]);
//        die;
    }



    //app账号密码登陆
    public function appLoging()
    {

        $staff['fans_id'] = 1;

        $staff['uniacid'] = 8895;

        $user = longbingGetUser($staff['fans_id'], $staff['uniacid']);

        $result['user'] = $user;

        $result['user_id'] = $staff['fans_id'];
        //生成缓存
        $autograph = longbingCreateToken();

        setCache($autograph, $user, 3600, $this->uniacid);

        $result['autograph'] = $autograph;

        return $this->success($result);



        //获取参数
        $input = $this->_input;
        if (!isset($input['login']['account']) || empty($input['login']['account'])) return $this->error(lang('not account'));
        if (!isset($input['login']['passwd']) || empty($input['login']['passwd'])) return $this->error(lang('not passwd'));
        //账号
        $account = $input['login']['account'];
        //密码
        $passwd = $input['login']['passwd'];
        //获取账号信息
        $staff = longbingGetStaff($account);
        if (empty($staff)) return $this->error(lang("account  or passwd error"));
        //检查密码
        $check = longbingCheckPasswd($passwd, $staff['offset'], $staff['passwd']);
        //
        $result = [];
        if ($check) {
            unset($staff['offset']);
            unset($staff['passwd']);
            $result['staff'] = $staff;
            $user = longbingGetUser($staff['fans_id'], $staff['uniacid']);
            $result['user'] = $user;
            $result['user_id'] = $staff['fans_id'];
            //生成缓存
            $autograph = longbingCreateToken();
            setCache($autograph, $user, 3600, $this->uniacid);
            $result['autograph'] = $autograph;

        } else {
            return $this->error(lang("account  or passwd error"));
        }



        return $this->success($result);
    }

    //百度小程序登陆
    public function baiduLogin()
    {


        //获取参数
        $param = $this->_param;
        //未获取code
        if (!isset($param['code'])) return $this->error(lang('not code'));
        //获取code 信息
        $code = $param['code'];
        //获取form_id
        $from_id = isset($param['from_id']) ? $param['from_id'] : '';
        //获取uniacid
        $uniacid = $this->uniacid;
        //初始化配送
        $setting_model = new AdminSetting();
        //获取百度配置
        $baidu = $setting_model->settingInfo(['uniacid' => $uniacid]);
        if (empty($baidu['client_id']) || empty($baidu['client_secret'])) {
            echo json_encode(['code' => 400, 'error' => '还未配置百度小程序']);
            exit;
        }
        $baidu_open_api_url = 'https://openapi.baidu.com/nalogin/getSessionKeyByCode';
        $client_id = $baidu['client_id'];
        $client_secret = $baidu['client_secret'];
        $url = $baidu_open_api_url . '?client_id=' . $client_id . '&sk=' . $client_secret . '&code=' . $code;
        $data = longbingCurl($url, '');
        $data = json_decode($data, true);
        if (empty($data) || isset($data['errno']) || !isset($data['openid']) || !isset($data['session_key']) || empty($data['openid']) || empty($data['session_key'])) return $this->error(lang('login error'));
        //获取用户信息
        $user_model = new User();
        $user = $user_model->getUser(['baidu_openid' => $data['openid'], 'deleted' => 0, 'uniacid' => $this->uniacid]);

        $result = [];
        if (empty($user)) {
            //openid
            $user['baidu_openid'] = $data['openid'];

            $user['openid'] = $data['openid'];
            //来自百度
            $user['from_id'] = 2;
            //默认昵称
            $user['nickName'] = getRandStr(4);
            //头像
            $user['avatarUrl'] = '';
            //uniacid
            $user['uniacid'] = $this->uniacid;
            //openGId
            $user['openGId'] = '';
            //pid
            $user['pid'] = $from_id;
            //qr_path
            $user['qr_path'] = '';
            //ip
            $user['ip'] = 0;
            //unionid
            $user['unionid'] = '';
            //city
            $user['city'] = '';
            //province
            $user['province'] = '';
            //country
            $user['country'] = '';
            //language
            $user['language'] = 'zh_CN';

            //创建用户信息
            $user_model = new User();
            $user = $user_model->createUser($user);

//            $user       = $user_model->getUser(['id'=>76085]);
            //判断是否创建成果
            if ($user) {

                //获取数据
                $user_model = new User();
                $user = $user_model->getUser(['baidu_openid' => $data['openid'], 'uniacid' => $this->uniacid]);

                //  检查用户的sk记录状态
                $skModel = new UserSk();
                $check_sk = $skModel->where('user_id', '=', $user['id'])->find();

                if ($check_sk) {
                    $skModel->update(['sk' => $data['session_key'], 'update_time' => time()], ['user_id' => $user['id']]);
                } else {
                    $skModel->sk = $data['session_key'];
                    $skModel->user_id = $user['id'];
                    $skModel->uniacid = $uniacid;
                    $skModel->create_time = time();
                    $skModel->update_time = time();
                    $skModel->save();
                }
                //  自动分配员工
                $configModel = new Config();

                //  获取配置
                $configInfo = $configModel->where('uniacid', '=', $this->uniacid)->find();

                //  判断有没有获取到配置信息，并且配置信息众是否有配置开关，并且开关打开没有
                //if ($configInfo && isset($configInfo['auto_switch']) && $configInfo['auto_switch'] && $from_id == 0) {
                if ($configInfo && $from_id == 0) {
                    //  判断有没有分配方式
                    if ($configInfo && isset($configInfo['auto_switch_way']) && $configInfo['auto_switch_way']) {

                        $tmpClientId = $user['id'];
                        if ($tmpClientId) {
                            $clientInfo = false;
                            $prefix = \think\facade\Config::get('database.connections.mysql.prefix');
                            //  随机分配
                            if ($configInfo['auto_switch_way'] == 1) {

                                //$sql = "select * from " . $prefix . "longbing_card_user_info where uniacid = $uniacid AND is_staff = 1 AND is_default = 1 AND fans_id != 0 order by rand() limit 0,1";

                                $sql =<<<SQL
SELECT
	b.*
FROM
	{$prefix}longbing_card_user as a
LEFT JOIN {$prefix}longbing_card_user_info as b
on  a.id = b.fans_id
WHERE
	a.uniacid = {$uniacid}
AND	b.uniacid = {$uniacid}
AND b.is_staff = 1
AND b.is_default = 1
AND b.fans_id != 0
ORDER BY
	rand()
LIMIT 0,
 1
SQL;


                                $clientInfo = Db::query($sql);

                            }
                            //  按顺序分配
                            if ($configInfo['auto_switch_way'] == 2) {
                                //$sql = "select * from " . $prefix . "longbing_card_user_info where uniacid = $uniacid AND is_staff = 1 AND is_default = 1 AND fans_id != 0 order by auto_count ASC limit 0,1";

                                $sql =<<<SQL
SELECT
	b.*
FROM
	{$prefix}longbing_card_user as a
LEFT JOIN {$prefix}longbing_card_user_info as b
on  a.id = b.fans_id
WHERE
	a.uniacid = {$uniacid}
AND	b.uniacid = {$uniacid}
AND b.is_staff = 1
AND b.is_default = 1
AND b.fans_id != 0
ORDER BY
	auto_count ASC
LIMIT 0,
 1
SQL;

                                $clientInfo = Db::query($sql);
                            }


                            if ($clientInfo) {
                                //获取分配员工
                                $clientInfo = $clientInfo[0];
                                //获取员工id
                                $tmpStaffId = $clientInfo['fans_id'];
                                $auto_count = $clientInfo['auto_count'];
                                if (empty($auto_count)) $auto_count = 0;
                                $auto_count = $auto_count + 1;
                                //生成客户关系
                                $collectionModel = new Collection();
                                //uniacid
                                $collectionModel->uniacid = $this->uniacid;
                                //用户id
                                $collectionModel->uid = $tmpClientId;
                                $collectionModel->to_uid = $tmpStaffId;
                                $collectionModel->from_uid = $tmpStaffId;
                                $collectionModel->status = 1;
                                //是否是自动分配
                                $collectionModel->is_auto = 1;
                                $autoResult = $collectionModel->save();
                                //更新用户和员工数据
                                if ($autoResult) {
                                    $user['autoCardId'] = $tmpStaffId;
                                    $userModel = new User();
                                    //更新用户的pid
                                    $user['pid'] = $tmpStaffId;
                                    $user['last_staff_id'] = $tmpStaffId;
                                    $userModel->updateUser(['id' => $user['id']], ['pid' => $tmpStaffId, 'last_staff_id' => $tmpStaffId]);
                                    //更新员工自动分配数据
                                    $userInfoModel = new UserInfo();
                                    $data = $userInfoModel->updateUser(['fans_id' => $tmpStaffId], ['auto_count' => $auto_count]);
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!empty($user)) {

            if(!isset($user['avatarUrl']) || empty($user['avatarUrl']) ) $user['avatarUrl'] =  LongbingDefault::$avatarImgUrl;

            $result['user'] = $user;
            $result['user_id'] = $user['id'];
            $autograph = longbingCreateToken();
            setCache($autograph, $user, 3600, $this->uniacid);
            $result['autograph'] = $autograph;
            $result['baidu_openid'] = $data['openid'];
            $result['session_key'] = $data['session_key'];
            $userPhoneModel = new UserPhone();
            $phone = $userPhoneModel->where([['user_id', '=', $user['id']], ['uniacid', '=', $uniacid]])->find();
            $result['user']['phone'] = !empty($phone['phone']) ? $phone['phone'] : '';

        }
        return $this->success($result);
    }



    /**
     * @Purpose: 小程序登陆接口
     *
     * @Param: string $code 小程序传过来的登陆code
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    function douyinLogin()
    {
        //获取token
        if (!isset($this->_param['code']) || !$this->_param['code']) {

            return $this->error(['code' => 400, 'error' => 'need code']);

        }

        global $_GPC, $_W;

        $code    = $this->_param['code'];

        $uniacid = $this->_param['i'];
        //  是否是微擎
        $config = longbingGetAppConfig($this->uniacid);

        $appid     = $config['dy_appid'];

        $appsecret = $config['dy_secret'];

        $from_id = isset( $this->_param[ 'from_id' ] ) ? $this->_param[ 'from_id' ] : '';
        //新增19.12.3
        if(!is_numeric( $from_id ) ){
            $result = longbingGetWxCode($from_id ,$this->uniacid , $is_update = false);
            if(!is_null($result) && array_key_exists("data", $result) ){
                $result = \think\Collection::make($result['data'])->toArray();
                if(array_key_exists("user_id", $result) ){
                    $from_id = $result['user_id'] ;
                }else if(array_key_exists("pid", $result) ){
                    $from_id = $result['pid'] ;
                }

            }
        }

        $is_qr = isset($this->_param['is_qr']) ? $this->_param['is_qr'] : '';

        $encryptedData = isset($this->_param['encryptedData']) ? $this->_param['encryptedData'] : '';

        $iv = isset($this->_param['iv']) ? $this->_param['iv'] : '';

        $userModel = new User();

        $dy_url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';

        $params = array(

            'appid'     => $appid,

            'secret'    => $appsecret,

            'code'      => $code,

            //  'grant_type'    => 'authorization_code',
        );

        $params = \GuzzleHttp\json_encode($params);

        $info = longbingCurl($dy_url, $params,'POST');

        $info = @json_decode($info, true);

        $info = $info['data'];

        if (!is_array($info)) {

            echo json_encode(['code' => 402, 'error' => 'need code' . $info]);

            exit;
        }
        //  微信端返回错误
        if (isset($info['errcode'])) {

            echo json_encode(['code' => 402, 'error' => $info['errcode'] . ', errmsg: ' . $info['errmsg']]);
            exit;
        }
        if (!isset($info['session_key'])) {

            echo json_encode(['code' => 402, 'error' => 'session_key not exists']);

            exit;
        }


        $session_key = $info['session_key'];
//
        $openGId     = '';

//        if ($encryptedData) {
//
//            $data = null;
//            //  解密
//            $errCode = decryptDataLongbing($appid, $session_key, $encryptedData, $iv, $data);
//
//            //  判断解密是否有错误
//            if ($errCode == 0) {
//                $data = json_decode($data, true);
//                $openGId = $data['openGId'];
//            }
//        }
        $randName = getRandStr(4);

        if (!isset($info['openid'])) {
            echo json_encode(['code' => 402, 'error' => 'openid not exists']);
            exit;
        }

        $openid  = $info['openid'];

        $unionid = isset($info['unionid']) ? $info['unionid'] : '';


        $user = '';
        //  检查用户有没有从获客文章来的数据
        if ($unionid) {
            $userFromArticle = $userModel->where([['unionid', '=', $unionid], ['openid', '<>', $openid],
                ['uniacid', '=', $uniacid], ['is_article', '=', 1]])->find();

            $user = $userModel->where(['openid' => $openid, 'uniacid' => $uniacid])->find();
            if ($user && $userFromArticle) {
                $cardModel = new CardCount();
                $cardModel->update(['user_id' => $user->id,], ['user_id' => $userFromArticle->id]);
                $user->unionid = $unionid;
                $user->save();
            }
        }
        if (!$user) {
            $user = $userModel->where([['openid', '=', $openid], ['uniacid', '=', $uniacid]])->find();
        }


        //新用户
        if (!$user) {

            $insertData = ['openid' => $openid];
//            $insertData['nickName'] = $randName;
            $insertData['scene'] = isset($this->_param['scene']) ? $this->_param['scene'] : 0;


            //获取系统设置
            $whereSetting['uniacid']=$uniacid;
            //file_put_contents(APP_PATH."/a.txt",'unionid：'.$uniacid, FILE_APPEND | LOCK_EX);

            $setting =Db::name('longbing_card_config')->where(['uniacid'=>$uniacid])->find();

            $formUser = $userModel->where(['id' => $from_id, 'uniacid' => $uniacid])->find();
            //开启分销的时候特殊处理,当开启分销状态，并且邀请用户是分销员时，绑定对应关系
            if($setting['distribution_user_examine']==1 && $formUser['distribution']==2 && $formUser['is_staff']==0) {
                //新增判断邀请用户是否是分销员，如果是分销员，不进行绑定，在审核分销员的时候进行绑定
                $insertData['pid']=$from_id;
            }
            else if($setting['distribution_user_examine']== 0){

                $insertData['pid']=$from_id;
            }

            $insertData['uniacid'] = $uniacid;
            $insertData['is_qr'] = $is_qr;
            $insertData['unionid'] = $unionid;
            $insertData['ip'] = 0;
            $insertData['is_staff'] = 0;
            if ($openGId) {
                $insertData['openGId'] = $openGId;
            }

            if (isset($this->_param['is_group'])) {
                $insertData['is_group'] = $this->_param['is_group'];
            }
            if (isset($this->_param['type'])) {
                $insertData['type'] = $this->_param['type'];
            }
            if (isset($this->_param['target_id'])) {
                $insertData['target_id'] = $this->_param['target_id'];
            }

            $result = $userModel->save($insertData);

            if ($result) {
                $uid = $userModel->id;

                $user = $userModel->where(['openid' => $openid, 'uniacid' => $uniacid])->find();
                if ($openGId) {
                    $user['openGId_2'] = $openGId;
                }
                $user['phone'] = '';

                //红包邀请
                if(!empty($from_id)&&!empty($this->_param['redbag_active_id'])){
                    //邀请模型
                    $invitation = new Invitation();

                    // dump($from_id,$user['id'],$this->_param['redbag_active_id'],$uniacid);exit;
                    //邀请
                    $invitation->addInvitation($from_id,$user['id'],$this->_param['redbag_active_id'],$uniacid);
                }
            }

            //  自动分配员工
            $configModel = new Config();

            //  获取配置
            $configInfo = $configModel->where('uniacid', '=', $uniacid)->find();
            //  判断有没有获取到配置信息，并且配置信息众是否有配置开关，并且开关打开没有
            //if ($configInfo && isset($configInfo['auto_switch']) && $configInfo['auto_switch'] && $from_id == 0) {
            if ($configInfo  && $from_id == 0) {
                //  判断有没有分配方式
                if ($configInfo && isset($configInfo['auto_switch_way']) && $configInfo['auto_switch_way']) {
                    $tmpClientId = $userModel->id;
                    if ($tmpClientId) {
                        $clientInfo = false;
                        $prefix = \think\facade\Config::get('database.connections.mysql.prefix');

                        //  随机分配
                        if ($configInfo['auto_switch_way'] == 1) {

                            //$sql = "select * from " . $prefix . "longbing_card_user_info where uniacid = $uniacid AND is_staff = 1 AND is_default = 1 AND fans_id != 0 order by rand() limit 0,1";

                            $sql =<<<SQL
SELECT
	b.*
FROM
	{$prefix}longbing_card_user as a
LEFT JOIN {$prefix}longbing_card_user_info as b
on  a.id = b.fans_id
WHERE
	a.uniacid = {$uniacid}
AND	b.uniacid = {$uniacid}
AND b.is_staff = 1
AND b.is_default = 1
AND b.fans_id != 0
ORDER BY
	rand()
LIMIT 0,
 1
SQL;


                            $clientInfo = Db::query($sql);

                        }
                        //  按顺序分配
                        if ($configInfo['auto_switch_way'] == 2) {
                            //$sql = "select * from " . $prefix . "longbing_card_user_info where uniacid = $uniacid AND is_staff = 1 AND is_default = 1 AND fans_id != 0 order by auto_count ASC limit 0,1";

                            $sql =<<<SQL
SELECT
	b.*
FROM
	{$prefix}longbing_card_user as a
LEFT JOIN {$prefix}longbing_card_user_info as b
on  a.id = b.fans_id
WHERE
	a.uniacid = {$uniacid}
AND	b.uniacid = {$uniacid}
AND b.is_staff = 1
AND b.is_default = 1
AND b.fans_id != 0
ORDER BY
	auto_count ASC
LIMIT 0,
 1
SQL;

                            $clientInfo = Db::query($sql);
                        }
                        // file_put_contents(APP_PATH."/a.txt",'clientInfo：'.json_encode($clientInfo), FILE_APPEND | LOCK_EX);

                        if ($clientInfo) {
                            $clientInfo = $clientInfo[0];
                            $tmpStaffId = $clientInfo['fans_id'];
                            $auto_count = $clientInfo['auto_count'];
                            if (empty($auto_count)) $auto_count = 0;
                            $auto_count = $auto_count + 1;
                            $collectionModel = new Collection();
                            $collectionModel->uniacid = $uniacid;
                            $collectionModel->uid = $tmpClientId;
                            $collectionModel->to_uid = $tmpStaffId;
                            $collectionModel->from_uid = $tmpStaffId;
                            $collectionModel->status = 1;
                            $collectionModel->is_auto = 1;
                            $autoResult = $collectionModel->save();
                            //file_put_contents(APP_PATH."/a.txt",'autoResult：'.$autoResult, FILE_APPEND | LOCK_EX);
                            if (!empty($autoResult)) {
                                $user['autoCardId'] = $tmpStaffId;
//                              $userModel->pid       = $tmpStaffId;
//                              $userModel->last_staff_id = $tmpStaffId;
//                              $userModel->save();
                                //更新用户的pid
                                $userModel = new User();
                                $user['pid'] = $tmpStaffId;
                                $user['last_staff_id'] = $tmpStaffId;
                                //file_put_contents(APP_PATH."/a.txt",'setting：'.json_encode($setting), FILE_APPEND | LOCK_EX);
                                $updateUser=$setting['distribution_user_examine'] == 0
                                    ? ['last_staff_id' => $tmpStaffId,'pid'=>$tmpStaffId]
                                    : ['last_staff_id' => $tmpStaffId];
                                //file_put_contents(APP_PATH."/a.txt","updateUser：".json_encode($updateUser), FILE_APPEND | LOCK_EX);
                                $userModel->updateUser(['id' => $user['id']],$updateUser );
                                //更新员工分配信息
                                $userInfoModel = new UserInfo();
                                $data = $userInfoModel->updateUser(['fans_id' => $tmpStaffId], ['auto_count' => $auto_count]);
//                              $data = $userInfoModel->where( [ 'id' => $clientInfo[ 'id' ] ] )
//                                            ->inc( 'auto_count' );
                            }
                        }
                    }
                }
            }

        } else { //老用户

            //处理第三方平台ID
            if ($unionid) {
                $user->unionid = $unionid;
                $user->save();
            }

            $userPhoneModel = new UserPhone();
            $phone = $userPhoneModel->where([['user_id', '=', $user['id']], ['uniacid', '=', $uniacid]])->find();
            $uid = $user['id'];
            $user['phone'] = $phone ? $phone['phone'] : '';
            if ($openGId) {
                $user['openGId_2'] = $openGId;
            }
        }

        if (!$uid) {
            echo json_encode(['code' => 402, 'error' => 'login fail']);
            exit;
        }
        //By.jingshuixian 更新用户最新的信息
        UserService::delUserInfoCache($this->uniacid,$uid) ;
        //  检查用户的sk记录状态
        $skModel = new UserSk();
        $check_sk = $skModel->where('user_id', '=', $uid)->find();
        //        zDump($check_sk);
        if ($check_sk) {
            //            $check_sk->sk = $session_key;
            //            $check_sk->save();
            $skModel->update(['sk' => $session_key, 'update_time' => time()], ['user_id' => $uid]
            );
        } else {
            $skModel->sk = $session_key;
            $skModel->user_id = $uid;
            $skModel->uniacid = $uniacid;
            $skModel->create_time = time();
            $skModel->update_time = time();
            $skModel->save();
        }

        $_W['uid'] = $uid;

        //  是否是微擎
        if (defined('IS_WEIQIN') && IS_WEIQIN) {

            $user = handleImagesWe7Local($user, ['qr_path', 'pay_qr'], ',');
        }

        if (!isset($user['autoCardId'])) {

            $user['autoCardId'] = 0;
        }

        if (empty($user['last_staff_id'])) {

            $lastInfo = CardCount::alias('a')
                ->join('longbing_card_user b', 'a.to_uid = b.id')
                ->where(['a.user_id' => $uid, 'b.is_staff' => 1])
                ->order(['a.id' => 'desc'])
                ->limit(1)
                ->find();


            if ($lastInfo) {
                $user['last_staff_id'] = $lastInfo['to_uid'];
            }
        }else{
            $staff_user = $userModel->where(['id'=>$user['last_staff_id'],'is_staff'=>1])->find();

            if(empty($staff_user)){
                $lastInfo = CardCount::alias('a')
                    ->join('longbing_card_user b', 'a.to_uid = b.id')
                    ->where(['a.user_id' => $uid, 'b.is_staff' => 1])
                    ->order(['a.id' => 'desc'])
                    ->limit(1)
                    ->find();
                if ($lastInfo) {
                    $user['last_staff_id'] = $lastInfo['to_uid'];
                }
            }
        }

        //  有分享人
        if ($from_id) {

            $user['last_staff_id'] = $from_id;
        }


        $key = 'longbing_user_autograph_' . $uid;
        $key = md5($key);
        $user = $user->toArray();


        $user['need_auth'] = 0;
        if (!$user['avatarUrl']) {
            $user['need_auth'] = 1;
        }

        $result = setCache($key, $user, 7200, $uniacid);

        if (!$result) {
            echo json_encode(['code' => 402, 'error' => 'login fail']);
            exit;
        }

        if (!isset($user['autoCardId'])) {
            $user['autoCardId'] = 0;
        }
        //获取sk数据
        longbingGetUserSk($uid, $uniacid, true);
        //By.jingshuixian  判断是否需要初始化第一个用户为员工
        event("UserLoginApp" , $user);
        //判断last_staff_id是否是员工 chenniang
        $staff_user = $userModel->where(['id'=>$user['last_staff_id'],'is_staff'=>1])->count();
        //如果不是
        if(empty($staff_user)){
            //模型
            $collectionModel = new Collection();
            //分配一个
            $user['last_staff_id'] = $collectionModel->getCard($uid,$uniacid);
        }

        if(!isset($user['avatarUrl']) || empty($user['avatarUrl']) ) $user['avatarUrl'] =  LongbingDefault::$avatarImgUrl;
        //By.jingshuixian 更新用户最新的信息
        UserService::delUserInfoCache($this->uniacid,$uid) ;

        echo json_encode(['code' => 200, 'data' => ['user_id' => $uid, 'user' => $user, 'autograph' => $key]]);
//        die;
    }

    //返回成功
    public function success($data, $code = 200)
    {
        $result['data'] = $data;
        $result['code'] = $code;
        $result['sign'] = null;
        //复杂的签名
        //      if(isset($this->_user['keys'])){
        //          $result['sign'] = rsa2CreateSign($this->_user['keys'] ,json_encode($data));
        //      }
        //简单的签名
        if (!empty($this->_token)) $result['sign'] = createSimpleSign($this->_token, is_string($data) ? $data : json_encode($data));
        return $this->response($result, 'json', $code);
    }

    //返回错误数据
    public function error($msg, $code = 400)
    {
        $result['error'] = $msg;
        $result['code'] = $code;
        return $this->response($result, 'json', $code);
    }

    //response
    protected function response($data, $type = 'json', $code = 200)
    {
        return Response::create($data, $type)->code($code);
    }
}
